package com.cdu.util;


import com.cdu.form.FileForm;

import org.apache.commons.lang.StringUtils;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author: Nemo Chen(姓名) 764291197@qq.com(邮箱) cfh10260108(微信)
 * @date: 2020/1/7 14:26
 * @Description:
 */
public class FastDFSUtils {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(FastDFSUtils.class);
    private static TrackerClient trackerClient = null;
    private static TrackerServer trackerServer = null;
    private static StorageServer storageServer = null;
    private static StorageClient storageClient = null;
    private static String TrackerUrl = "你的IP";

    static {
        try {
            String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
            ClientGlobal.init(filePath);
            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getTrackerServer();
            storageServer = trackerClient.getStoreStorage(trackerServer);
        } catch (Exception e) {
            logger.error("FastDFS Client Init Fail!", e);
        }
    }

    public static String[] upload(String fileName, byte[] content, String ext, String author) {
        logger.info("File Name: " + fileName + "File Length:" + content.length);

        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] = new NameValuePair("author", author);

        long startTime = System.currentTimeMillis();
        String[] uploadResults = null;
        try {
            storageClient = new StorageClient(trackerServer, storageServer);
            uploadResults = storageClient.upload_file(content, ext, meta_list);
        } catch (IOException e) {
            logger.error("IO Exception when uploadind the file:" + fileName, e);
        } catch (Exception e) {
            logger.error("Non IO Exception when uploadind the file:" + fileName, e);
        }
        logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");

        if (uploadResults == null) {
            logger.error("upload file fail, error code:" + storageClient.getErrorCode());
        }
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];

        logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
        return uploadResults;
    }

    public static FileInfo getFile(String groupName, String remoteFileName) {
        try {
            storageClient = new StorageClient(trackerServer, storageServer);
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (IOException e) {
            logger.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    public static InputStream downFile(String groupName, String remoteFileName) {
        try {
            storageClient = new StorageClient(trackerServer, storageServer);
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            InputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        } catch (IOException e) {
            logger.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }

    public static void deleteFile(String groupName, String remoteFileName)
            throws Exception {
        storageClient = new StorageClient(trackerServer, storageServer);
        int i = storageClient.delete_file(groupName, remoteFileName);
        logger.info("delete file successfully!!!" + i);
    }

    public static String[] getFileUrl(MultipartFile multipartFile) {
        String[] fileAbsolutePath = {};
        if (multipartFile != null) {
            String fileName = multipartFile.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
                try {
                    byte[] file_buff = multipartFile.getBytes();
                    fileAbsolutePath = upload(multipartFile.getName(), file_buff, ext, "cfh");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileAbsolutePath;
    }

    public static FileForm upload(MultipartFile multipartFile) {
        FileForm fileForm = new FileForm();
        String[] resultArray = getFileUrl(multipartFile);
        if (resultArray != null) {
            fileForm.setGroupName(resultArray[0]);
            fileForm.setFileKey(resultArray[1]);
            fileForm.setFileUrl(TrackerUrl + resultArray[0] + "/" + resultArray[1]);
            fileForm.setFileSize(multipartFile.getSize());
            fileForm.setFileName(multipartFile.getName());
        }
        return fileForm;
    }
}